package com.mid;

/**
 * Created by Lxk on 2020/2/19.
 */

class NumMatrix {

    private final int[][] matrix;

    private final int col;

    private final int row;

    public NumMatrix(int[][] matrix) {
        this.matrix = matrix;
        if (matrix != null) {
            this.row = matrix.length;
            if (matrix[0] != null) {
                this.col = matrix[0].length;
            } else {
                this.col = 0;
            }
        } else {
            this.row = 0;
            this.col = 0;
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (row1 < 0) row1 = 0;
        if (row2 >= this.row) row2 = this.row - 1;
        if (col1 < 0) col1 = 0;
        if (col2 >= this.col) col2 = this.col - 1;
        int sum = 0;
        for (int i = row1; i <= row2; i++) {
            for (int j = col1; j <= col2; j++) {
                sum += this.matrix[i][j];
            }
        }
        return sum;
    }
}

public class Solution304 {

    public static void main(String[] args) {
        int[][] matrix = {
                {3, 0, 1, 4, 2},
                {5, 6, 3, 2, 1},
                {1, 2, 0, 1, 5},
                {4, 1, 0, 1, 7},
                {1, 0, 3, 0, 5}};
        NumMatrix numMatrix = new NumMatrix(matrix);
        System.out.println(numMatrix.sumRegion(2, 1, 4, 3));
    }

}
